<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use iflow\Response;

class userGroupModel extends QueryModel
{

    protected $table = 'user_group_table';

    public function getUserGroupList(string $groupName, int $user_group_type): Response
    {
        $query = $this->where([
            'status' => 1
        ]) -> order(['create_time' => 'desc']);

        if ($groupName !== '') {
            $query -> whereLike('user_group_name', "%{$groupName}%");
        }

        // 用户组所属类别
        if ($user_group_type) {
            $query -> where([
                'user_group_type' => $user_group_type
            ]);
        }

        $query = $query -> paginate([
            'page' => request() -> getParams('page'),
            'list_rows' => 10
        ]);
        $items = $query -> items();

        return $items ?
            message() -> success('查询成功', $items, [
                'count' => $query -> total(),
                'current' => $query -> lastPage()
            ]): message() -> nodata('暂无数据');
    }

    public function deleteGroup(int $user_group_id = 0): Response {
        $find = $this->where([
            'user_group_parent_id' => $user_group_id
        ]) -> findOrEmpty();
        if ($find -> isExists()) return message() -> update_failed('该用户组下还有子用户组无法删除');

        $user = (new userModel()) -> userByGroup($user_group_id);
        if ($user -> isExists()) return message() -> update_failed('该用户组下还有用户无法删除');

        $this->where([
            'user_group_id' => $user_group_id
        ]) -> delete();
        return message() -> success('删除用户组成功');
    }

    public function addUserGroup(string $user_group_name = '', int $user_group_parent_id = 0): Response {
        return $this->createData([
            'user_group_name' => $user_group_name,
            'user_group_parent_id' => $user_group_parent_id
        ]);
    }

    public function updateUserGroup(string $user_group_name, int $user_group_id): Response {
        return $this->updateInfo([
            'user_group_name' => $user_group_name
        ], [ 'user_group_id' => $user_group_id ]);
    }
}